package org.csu.mypetstore.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.csu.mypetstore.aspect.LogAnnotation;
import org.csu.mypetstore.commonResponse.CommonResponse;
import org.csu.mypetstore.domin.Account;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.MailService;
import org.csu.mypetstore.thread.RemoveCodeThread;
import org.csu.mypetstore.util.SMSUtils;
import org.csu.mypetstore.util.VerifyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Arrays;

@RestController
@RequestMapping("/accounts")
public class AccountController {


    @Autowired
    private AccountService accountService;
    @Autowired
    private SMSUtils smsUtils;

    public static CommonResponse<Account> isLogin(HttpSession session){
        Account loginUser=(Account) session.getAttribute("loginUser");
        if(loginUser==null){
            return CommonResponse.createForError("未登录");
        }

        return CommonResponse.createForSuccess("已登录",loginUser);
    }
    //查看是否登录
    @GetMapping("/islogin")
    public CommonResponse<Object> islogin(HttpSession session){
        Account loginUser=(Account) session.getAttribute("loginUser");
        if(loginUser == null){
            return CommonResponse.createForError("未登录");
        }
        return CommonResponse.createForSuccess("已登录",loginUser);
    }
    @GetMapping("/isExit")
    public CommonResponse<Account> isExit(@RequestParam String username){
        return accountService.getAccountByUsername(username);
    }

    //通过username和password查找用户
    @LogAnnotation(module="accounts",operation = "账号登录")
    @PostMapping("/token")
    public CommonResponse<Account> getAccountByUsernameAndPassword(@RequestParam String username,
                                                                   @RequestParam String password,
                                                                   @RequestParam String code,
                                                                   HttpSession session){
        CommonResponse<Account> commonResponse=accountService.getAccountByUsernameAndPassword(username,password);
        String serverCode = (String) session.getAttribute("VerifyCode");
        // 校验验证码
        if (null == serverCode || !serverCode.equalsIgnoreCase(code)) {
            return CommonResponse.createForError("验证码错误!");
        } else {
            if(commonResponse.isSuccess()){
                session.setAttribute("loginUser",commonResponse.getData());
            }
        }
        return  commonResponse;
    }


    //通过手机号发送验证码
    @GetMapping("/code")
    public CommonResponse<Object> sendCode(HttpSession session,@RequestParam String phone) {
        String code = smsUtils.Code();

        //新建线程类实现1分钟后删除code
        if(smsUtils.sendMsg(phone,code)){
            session.setAttribute("PhoneCode",code);
            RemoveCodeThread removeCodeThread = new RemoveCodeThread(session);
            removeCodeThread.start();
            return CommonResponse.createForSuccessMessage("验证码发送成功");

        }
        return CommonResponse.createForError("验证码发送失败");
    }

    //手机号登陆
    @LogAnnotation(module="accounts",operation = "手机号登录")
    @PostMapping("/loginphone")
    public CommonResponse<Account> loginPhone(@RequestParam String phone,
                                         @RequestParam String code,
                                         HttpSession session){
        CommonResponse<Account> commonResponse=accountService.getAccountByPhone(phone);
        if(commonResponse.isSuccess()){
            String code1 = (String) session.getAttribute("PhoneCode");
            if(code.equals(code1)){
                session.setAttribute("loginUser",commonResponse.getData());
                return CommonResponse.createForSuccess("登陆成功",commonResponse.getData());
            }
            return CommonResponse.createForError("验证码不正确");
        }
        return  commonResponse;
    }

    //退出登录
    @LogAnnotation(module="accounts",operation = "退出登录")
    @GetMapping("/logout")
    public CommonResponse<Object> logout(HttpSession session){
        try {
            session.removeAttribute("loginUser");
            return CommonResponse.createForSuccessMessage("退出登陆成功");
        }catch (Exception e){
            return CommonResponse.createForError("服务器出错了喵o(TヘTo)");
        }
    }

    //新增用户
    @LogAnnotation(module="accounts",operation = "账户注册")
    @PostMapping("")
    public CommonResponse<Account> insertAccount(@RequestBody Account account,@RequestParam String code,HttpSession session){
        String VerifyCode = (String) session.getAttribute("PhoneCode");
        if(VerifyCode.equals(code)){
            return accountService.insertAccount(account);
        }
        return CommonResponse.createForError();
    }
    //更新用户
    @LogAnnotation(module="accounts",operation = "修改账号")
    @PutMapping("")
    public CommonResponse<Account> updateAccount(@RequestBody Account account,HttpSession session){
        CommonResponse<Account> commonResponse=isLogin(session);
        if(commonResponse.getStatus()==0){
            return CommonResponse.createForError("未登录");
        }else {
            account.setUserid(commonResponse.getData().getUserid());
            CommonResponse<Account> commonResponse1=accountService.updateAccount(account);
            session.setAttribute("loginUser",commonResponse1.getData());
            return accountService.updateAccount(account);
        }
    }

    //通过QQ邮箱发送验证码
    @Autowired
    private MailService mailService;
    @LogAnnotation(module="accounts",operation = "向邮箱发送验证码")
    @PostMapping("/sendEmail")
    public CommonResponse<String> sendEmail(@RequestParam String email, HttpSession session){
        mailService.sendMimeMail(email, session);
        RemoveCodeThread removeCodeThread = new RemoveCodeThread(session);
        removeCodeThread.start();
        return CommonResponse.createForSuccess("发送成功");
    }

    //通过邮箱验证码修改邮箱
    @LogAnnotation(module="accounts",operation = "添加邮箱")
    @PostMapping("/addEmail")
    public CommonResponse<String> addEmail(@RequestParam String email,@RequestParam String code,HttpSession session){

        String username = ((Account) session.getAttribute("loginUser")).getUserid();
        String EmailCode = (String) session.getAttribute("EmailCode");
        String Email = (String) session.getAttribute("email");
        if(Email.equals(email) && EmailCode.equals(code)){
            Account account = accountService.getAccountByUsername(username).getData();
            session.setAttribute("loginUser",account);
            return mailService.addEmail(email,username);
        }
        return CommonResponse.createForError("邮箱或验证码不匹配");
    }

    @GetMapping("/getcode")
    public void getCode(HttpServletResponse response, HttpSession session) throws Exception {
        // 获取到session
        //使用自定义参数
        // 利用图片工具生成图片
        // 返回的数组第一个参数是生成的验证码，第二个参数是生成的图片
        Object[] objs = VerifyUtil.newBuilder()
                .setWidth(120)   //设置图片的宽度
                .setHeight(35)   //设置图片的高度
                .setSize(6)      //设置字符的个数
                .setLines(10)    //设置干扰线的条数
                .setFontSize(25) //设置字体的大小
                .setTilt(true)   //设置是否需要倾斜
                .setBackgroundColor(Color.LIGHT_GRAY) //设置验证码的背景颜色
                .build()         //构建VerifyUtil项目
                .createImage();  //生成图片
        // 将验证码存入Session
        session.setAttribute("VerifyCode", objs[0]);
        // 打印验证码
        System.out.println(objs[0]);

        // 设置redis值的序列化方式
//        redisTemplate.setValueSerializer(new StringRedisSerializer());
        // 在redis中保存一个验证码最多尝试次数
        // 这里采用的是先预设一个上限次数，再以reidis decrement(递减)的方式来进行验证
        // 这样有个缺点，就是用户只申请验证码，不验证就走了的话，这里就会白白占用5分钟的空间，造成浪费了
        // 为了避免以上的缺点，也可以采用redis的increment（自增）方法，只有用户开始在做验证的时候设置值，
        //    超过多少次错误，就失效；避免空间浪费
//        redisTemplate.opsForValue().set(("VERIFY_CODE_" + id), "3", 5 * 60, TimeUnit.SECONDS);

        // 将图片输出给浏览器
        BufferedImage image = (BufferedImage) objs[1];
        response.setContentType("image/png");
        OutputStream os = response.getOutputStream();
        ImageIO.write(image, "png", os);
    }
}
